package ar.uba.dc.cmovil.tripplanner.domain;

import android.content.Context;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;

public class TripsManager {

    static TripsManager this_instance;
    Context context;
    String trips_file = "trips_file";
    ArrayList<Trip> trips;

    private TripsManager() {
        this.trips = new ArrayList<Trip>();
    }

    public static TripsManager getInstance() {
        if (this_instance == null) {
            this_instance = new TripsManager();
        }
        return this_instance;
    }

    public void setContext(Context c) {
        context = c;
    }

    public void saveTrips() {
        try {
            FileOutputStream fos = context.openFileOutput(trips_file, Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(trips);
            os.close();
        } catch (IOException e) {

        }
    }

    public ArrayList<Trip> loadTrips() {
        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            fileInputStream = context.openFileInput(trips_file);
            objectInputStream = new ObjectInputStream(fileInputStream);

            this.trips = (ArrayList<Trip>) objectInputStream.readObject();

            return trips;
        } catch (FileNotFoundException e) {
            this.trips = new ArrayList<Trip>();

            return this.trips;
        } catch (IOException e) {
            throw new RuntimeException("error loading trips", e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("error loading trips", e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    //throw new RuntimeException("error closing trips' file", e);
                }
            }
        }
    }

    public void add(Trip trip) {
        this.trips.add(trip);
    }

    public void remove(Trip trip) {
        this.trips.remove(trip);
    }

    public ArrayList<Trip> getTrips() {
        return trips;
    }

    public Trip getTripById(String id) {
        for (Trip trip : trips) {
            if (trip.getId().toString().equals(id)) {
                return trip;
            }
        }
        return null;
    }
}
